package com.distributeredis.redis_springboot.springboothutoolsexportorimport.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.distributeredis.redis_springboot.springboothutoolsexportorimport.entity.Employee;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/test")
public class ExportAndImport {

    @PostMapping("/import")
    public String testImport(@RequestParam MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> list = reader.read(1);
        System.out.println(list);
        return "导入成功";
    }

    @GetMapping("/export")
    public String testExport(HttpServletResponse response) throws Exception {
        List<Employee> list = Arrays.asList(new Employee("小明", "12", "男"),
                new Employee("小红", "22", "女"));
        // 括号可以填写写出路径
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("userName","用户名");
        writer.addHeaderAlias("age","年龄");
        writer.addHeaderAlias("sex","性别");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);
        writer.renameSheet("表一");
        // //创建新的sheet页  writer.setSheet


        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
        return "导出成功";
    }
}
